package ru.ssau.customerManagement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.ssau.customerManagement.controller.ServerSideController;
import ru.ssau.customerManagement.controller.ServerSideControllerImpl;
import ru.ssau.customerManagement.controller.threads.server.Worker;
import ru.ssau.customerManagement.model.DBModel;
import ru.ssau.customerManagement.model.Model;
import ru.ssau.customerManagement.model.db.DatabaseHelper;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Locale;

/**
 * Created by illabefat on 25.11.14.
 */
public class ServerMain {
    private static final Logger logger = LoggerFactory.getLogger(ServerMain.class);

    private static ServerSideController controller;

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        logger.info("Starting...");

        //Oracle... NLS...
        Locale locale_en = new Locale("en");
        Locale.setDefault(locale_en);

        String connectionString = getConnectionString();
        Model model = new DBModel(new DatabaseHelper(connectionString));
        controller = new ServerSideControllerImpl(model);

        ServerSocket serverSocket = new ServerSocket(5555);

        logger.info("Successfully loaded all stuff");

        while (true)
        {
            Socket client = serverSocket.accept();
            logger.info("Client connected");
            new Thread(new Worker(client, controller)).start();
        }
    }

    private static String getConnectionString()
    {
        try {
            BufferedReader in = new BufferedReader(new FileReader("db_info.txt"));
            String connectionString = in.readLine();
            return connectionString;
        } catch (FileNotFoundException e) {
            logger.error("Failed to read connection string");
            throw new RuntimeException(e);
        } catch (IOException e) {
            logger.error("Failed to read connection string");
            throw new RuntimeException(e);
        }
    }
}
